const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();
const fs = require('fs');
const route = require('koa-route');
const send = require('koa-send');
const path = require('path');

var http = require('http');    
var url = require('url');   

var server = http.createServer(function (req, res) {  
    var pathname = url.parse(req.url).pathname;  
    var realPath = "resources" + pathname;//所有文件都存在与resources目录下  
    console.log(realPath);  
    fs.exists(realPath, function (exists) {//判断文件是否存在  
        if (!exists) {  
            res.writeHead(404,{"Content-Type":"text/plain"});    
            res.write("404\nNot Found!\n");    
            res.end();    
        } else {  
            fs.readFile(realPath, "binary", function (err, file) {  
                    res.writeHead(200, {  
                        'Content-Type': 'text/html'  
                    });  
                    res.write(file, "binary");  
                    res.end();  
            });  
        }  
    });  
});  

app.use(route.get('/about', async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = 'jjjjjjjjj';
    // ctx.response.type = 'text/html';
    // ctx.response.body = '<h1>v0.1.1</h1>';
}));
// 对于任何请求，app将调用该异步函数处理请求：
app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    await next(); // 调用下一个middleware
});

app.use(async (ctx, next) => {
    const start = new Date().getTime(); // 当前时间
    await next(); // 调用下一个middleware
    const ms = new Date().getTime() - start; // 耗费时间
    console.log(`Time: ${ms}ms`); // 打印耗费时间
});

app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = fs.createReadStream('./index.html');
    // ctx.response.type = 'text/html';
    // ctx.response.body = '<h1>v0.1.1</h1>';
});
app.use(route.get('/down', async (ctx, next) => {
    var fileName = 'ssd.apk';
    // Set Content-Disposition to "attachment" to signal the client to prompt for download.
    // Optionally specify the filename of the download.
    // 设置实体头（表示消息体的附加信息的头字段）,提示浏览器以文件下载的方式打开
    // 也可以直接设置 ctx.set("Content-disposition", "attachment; filename=" + fileName);
    ctx.attachment(fileName);
    await send(ctx, fileName, { root: __dirname + '/resources' });
}));
app.use(route.get('/downloads', async (ctx, next) => {
    await next();
    // try{
    // 	ctx.response.attachment('./ssd.apk');
    // }catch(err){
    // 	console.log(err);
    // }
	//this.response.download('./ssd.apk'); 
	//ctx.body = fs.createReadStream('./ssd.apk');
	 // if ('/' == ctx.path) return ctx.body = 'Try GET /package.json';
    //await send(ctx, path.join(__dirname, './ssd.apk'));
	 // await send(ctx, './ssd.apk');
      // try {
      //      // var src = fs.createReadStream('./ssd.apk');
      //      ctx.response.send(__dirname+'/ssd.apk');
      //      // ctx.body = src;
      //  } catch (err) {
      //      // ctx.body = fillError(err)
      //      console.log(err);
      //  }
  await send(ctx, './ssd.apk');

}));
// 在端口3000监听:
app.listen(3333);
console.log('app started at port 3333...');

// router.get('/get/:id/xx', async (ctx,next) =>{
//     await next();
//     let arr=[  
//        {'name':'zfeig','age':25,'sex':'male','addr':'广东深圳'},  
//        {'name':'lisi','age':28,'sex':'male','addr':'四川成都'},  
//        {'name':'chenfeng','age':24,'sex':'female','addr':'湖北武汉'},  
//        {'name':'zhangyong','age':32,'sex':'male','addr':'浙江杭州'},  
//        {'name':'zfeig','age':22,'sex':'female','addr':'广东广州'},  
//        {'name':'zfeig','age':24,'sex':'male','addr':'湖南长沙'},  
//        {'name':'zfeig','age':29,'sex':'female','addr':'江苏南京'}  
//     ];
//     ctx.response.type = 'text/html';
//     ctx.response.body = ctx.session.user.username;
//     // console.log(ctx.params.id);
//     console.log(ctx.session.user);
// });
// router.post('/post', koaBody(),async (ctx,next) =>{
//     let arr=[  
//        {'name':'zfeig','age':25,'sex':'male','addr':'广东深圳'},  
//        {'name':'lisi','age':28,'sex':'male','addr':'四川成都'},  
//        {'name':'chenfeng','age':24,'sex':'female','addr':'湖北武汉'},  
//        {'name':'zhangyong','age':32,'sex':'male','addr':'浙江杭州'},  
//        {'name':'zfeig','age':22,'sex':'female','addr':'广东广州'},  
//        {'name':'zfeig','age':24,'sex':'male','addr':'湖南长沙'},  
//        {'name':'zfeig','age':29,'sex':'female','addr':'江苏南京'}  
//     ];
//     console.log(ctx.request.body);
//     ctx.response.type = 'text/html';
//     ctx.response.body =arr;
// });